using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using WPFServices.Commands;
using WPFServices.Models.Domain;
using WPFServices.Services.DomainService.Material;
using WPFServices.Services.DomainService.Productinfo;

namespace WPFServices.ViewModels.DomainViewModel.Material
{
    public class MaterialSelectionViewModel : BaseViewModel
    {
        private readonly MaterialService _materialService;
        private readonly ProductService _productService;
        private ObservableCollection<MaterialDto> _materials;
        private ObservableCollection<ProductDto> _products;
        private MaterialDto _selectedMaterial;
        private ProductDto _selectedProduct;
        private bool _isLoading;
        private int _currentPage = 1;
        private int _pageSize = 10;
        private int _totalCount;
        private int _totalPages;
        private string _currentTab = "Material"; // "Material" 或 "Product"

        public MaterialSelectionViewModel()
        {
            _materialService = new MaterialService();
            _productService = new ProductService();
            _materials = new ObservableCollection<MaterialDto>();
            _products = new ObservableCollection<ProductDto>();
            
            LoadDataCommand = new RelayCommand(async _ => await LoadDataAsync());
            SwitchTabCommand = new RelayCommand(_ => SwitchTab(_));
            FirstPageCommand = new RelayCommand(_ => GoToFirstPage(), _ => CurrentPage > 1);
            PreviousPageCommand = new RelayCommand(_ => GoToPreviousPage(), _ => CurrentPage > 1);
            NextPageCommand = new RelayCommand(_ => GoToNextPage(), _ => CurrentPage < TotalPages);
            LastPageCommand = new RelayCommand(_ => GoToLastPage(), _ => CurrentPage < TotalPages);
            ConfirmCommand = new RelayCommand(_ => Confirm(), _ => CanConfirm());
            CancelCommand = new RelayCommand(_ => Cancel());

            _ = LoadDataAsync();
        }

        #region 属性
        public ObservableCollection<MaterialDto> Materials
        {
            get => _materials;
            set => SetProperty(ref _materials, value);
        }

        public ObservableCollection<ProductDto> Products
        {
            get => _products;
            set => SetProperty(ref _products, value);
        }

        public MaterialDto SelectedMaterial
        {
            get => _selectedMaterial;
            set => SetProperty(ref _selectedMaterial, value);
        }

        public ProductDto SelectedProduct
        {
            get => _selectedProduct;
            set => SetProperty(ref _selectedProduct, value);
        }

        public bool IsLoading
        {
            get => _isLoading;
            set => SetProperty(ref _isLoading, value);
        }

        public int CurrentPage
        {
            get => _currentPage;
            set => SetProperty(ref _currentPage, value);
        }

        public int PageSize
        {
            get => _pageSize;
            set => SetProperty(ref _pageSize, value);
        }

        public int TotalCount
        {
            get => _totalCount;
            set => SetProperty(ref _totalCount, value);
        }

        public int TotalPages
        {
            get => _totalPages;
            set => SetProperty(ref _totalPages, value);
        }

        public string CurrentTab
        {
            get => _currentTab;
            set
            {
                if (SetProperty(ref _currentTab, value))
                {
                    CurrentPage = 1;
                    _ = LoadDataAsync();
                }
            }
        }
        #endregion

        #region 命令
        public RelayCommand LoadDataCommand { get; }
        public RelayCommand SwitchTabCommand { get; }
        public RelayCommand FirstPageCommand { get; }
        public RelayCommand PreviousPageCommand { get; }
        public RelayCommand NextPageCommand { get; }
        public RelayCommand LastPageCommand { get; }
        public RelayCommand ConfirmCommand { get; }
        public RelayCommand CancelCommand { get; }
        #endregion

        #region 事件
        public event Action<object> CloseWindow;
        #endregion

        #region 方法
        private async Task LoadDataAsync()
        {
            try
            {
                IsLoading = true;
                
                if (CurrentTab == "Material")
                {
                    await LoadMaterialsAsync();
                }
                else
                {
                    await LoadProductsAsync();
                }
            }
            catch (Exception ex)
            {
                System.Windows.MessageBox.Show($"获取数据失败: {ex.Message}", "错误");
            }
            finally
            {
                IsLoading = false;
            }
        }

        private async Task LoadMaterialsAsync()
        {
            var searchDto = new SearchMaterialDto
            {
                PageIndex = CurrentPage,
                PageSize = PageSize
            };

            var result = await _materialService.GetMaterialsAsync(searchDto);

            Materials.Clear();
            if (result.Data != null)
            {
                foreach (var material in result.Data)
                {
                    Materials.Add(material);
                }
            }
            TotalCount = result.TotalCount;
            TotalPages = result.TotalPage;
        }

        private async Task LoadProductsAsync()
        {
            var searchDto = new SearchProductDto
            {
                PageIndex = CurrentPage,
                PageSize = PageSize
            };

            var result = await _productService.SearchProductAsync(searchDto);

            Products.Clear();
            if (result.Data != null)
            {
                foreach (var product in result.Data)
                {
                    Products.Add(product);
                }
            }
            TotalCount = result.TotalCount;
            TotalPages = result.TotalPage;
        }

        private void GoToFirstPage()
        {
            CurrentPage = 1;
            _ = LoadDataAsync();
        }

        private void GoToPreviousPage()
        {
            if (CurrentPage > 1)
            {
                CurrentPage--;
                _ = LoadDataAsync();
            }
        }

        private void GoToNextPage()
        {
            if (CurrentPage < TotalPages)
            {
                CurrentPage++;
                _ = LoadDataAsync();
            }
        }

        private void GoToLastPage()
        {
            CurrentPage = TotalPages;
            _ = LoadDataAsync();
        }

        private bool CanConfirm()
        {
            if (CurrentTab == "Material")
            {
                return SelectedMaterial != null;
            }
            else
            {
                return SelectedProduct != null;
            }
        }

        private void Confirm()
        {
            if (CurrentTab == "Material" && SelectedMaterial != null)
            {
                CloseWindow?.Invoke(SelectedMaterial);
            }
            else if (CurrentTab == "Product" && SelectedProduct != null)
            {
                CloseWindow?.Invoke(SelectedProduct);
            }
        }

        private void Cancel()
        {
            CloseWindow?.Invoke(null);
        }

        private void SwitchTab(object parameter)
        {
            if (parameter is string tabName)
            {
                CurrentTab = tabName;
            }
        }
        #endregion
    }
} 